/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.FormField;
import com.jb.web.context.WebContext;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;

import com.jb.faces.component.UIComponent;
import com.jb.faces.context.FacesContext;

import javax.servlet.http.HttpServletRequest;


public class DateTimeFieldRenderer extends FormItemRenderer {
    final String NEGETIVE_ONE = "-1";

    public void decode(FacesContext pCtx, UIComponent item) {
        FormField formField = (FormField) item;
        WebContext ctx = (WebContext) pCtx;
        HttpServletRequest request = ctx.getRequest();

        String year = request.getParameter(formField.getClientId() + "_y");
        String month = request.getParameter(formField.getClientId() + "_m");
        String day = request.getParameter(formField.getClientId() + "_d");

        String hour = request.getParameter(formField.getClientId() + "_h");
        String minute = request.getParameter(formField.getClientId() + "_mm");

        if ((year == null) || (month == null) || (day == null)) {
            return;
        }

        //        String second = request.getParameter(formField.getClientId() + "_s");
        //       String millisec = request.getParameter(formField.getClientId() + "_ms");
        if (NEGETIVE_ONE.equals(year) || NEGETIVE_ONE.equals(month) || NEGETIVE_ONE.equals(day)) {
            if (formField.getMandatory()) {
                ctx.addErrorMessage(this, "Please select a date");
                pCtx.renderResponse();

                return;
            } else {
                formField.setDecodedValue(null);

                return;
            }
        }

        String value = year + "/" + month + "/" + day + " " + hour + ":" + minute;

        try {
            Date date = new SimpleDateFormat("y/M/d h:m").parse(value);
            formField.setDecodedValue(date);
        } catch (ParseException e) {
            ctx.addErrorMessage(this, "Decode value failed" + value);
            pCtx.renderResponse();
        }
    }

    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        FormField formField = (FormField) itemToRender;
        StringBuffer html = new StringBuffer("");

        Date value = (Date) formField.getModelBean();

        int year = -1;
        int month = -1;
        int day = -1;
        int minute = -1;
        int hour = -1;

        if (value == null) {
            value = (Date) evaluateObject(pCtx, formField, formField.getDefaultValue());
        }

        if (value != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(value);
            year = cal.get(Calendar.YEAR);
            month = cal.get(Calendar.MONTH);
            day = cal.get(Calendar.DATE);
            minute = cal.get(Calendar.MINUTE);
            hour = cal.get(Calendar.HOUR_OF_DAY);
        }

        html.append("<div ").append(addTagProperty("style", formField.getStyle(pCtx), null))
            .append(addTagProperty("class", formField.getStyleClass(), null)).append(getEditScript(pCtx, formField))
            .append(">");
        html.append("<input type=\"hidden\" name=\"" + formField.getFieldName(pCtx) + "\" >");

        html.append("&nbsp;<SELECT name=\"" + formField.getClientId() + "_m\" />");

        DateFormatSymbols df = new DateFormatSymbols(pCtx.getSession().getLocale());
        String[] months = df.getShortMonths();

        html.append("<OPTION value=\"-1\"" + ((-1 == month) ? "selected" : "") + " ></OPTION>\n");

        for (int i = 0; i < (months.length - 1); i++) {
            int j = i + 1;
            html.append("<OPTION value=\"" + j + "\"" + ((i == month) ? "selected" : "") + " >" + months[i] +
                "</OPTION>\n");
        }

        html.append("</SELECT >");
        html.append("&nbsp;<SELECT name=\"" + formField.getClientId() + "_d\" />");

        html.append("<OPTION value=\"-1\"" + ((-1 == day) ? "selected" : "") + "></OPTION>\n");

        for (int i = 1; i < 32; i++)
            html.append("<OPTION value=\"" + i + "\"" + ((i == day) ? "selected" : "") + ">" + i + "</OPTION>\n");

        html.append("</SELECT >");

        html.append("&nbsp;<SELECT name=\"" + formField.getClientId() + "_y\" >");

        int year1 = Calendar.getInstance().get(Calendar.YEAR);

        html.append("<OPTION value=\"-1\"" + ((-1 == year) ? "selected" : "") + "></OPTION>\n");

        for (int i = year1 - 5; i < (year1 + 5); i++) {
            html.append("<OPTION value=\"" + i + "\" " + ((i == year) ? "selected" : "") + ">" + i + "</OPTION>\n");
        }

        html.append("</SELECT >");

        html.append("&nbsp;-<SELECT name=\"" + formField.getClientId() + "_h\" />");

        for (int i = 0; i < 24; i++)
            html.append("<OPTION value=\"" + i + "\"" + ((i == hour) ? "selected" : "") + ">" + i + "</OPTION>\n");

        html.append("</SELECT >");

        html.append("&nbsp;<SELECT name=\"" + formField.getClientId() + "_mm\" />");

        for (int i = 0; i < 4; i++)
            html.append("<OPTION value=\"" + (i * 15) + "\"" + (((i * 15) == minute) ? "selected" : "") + ">" +
                (i * 15) + " Minutes</OPTION>\n");

        html.append("</SELECT >");

        html.append("</div");

        return html;
    }
}
